package org.jeecg.modules.sggg.controller;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.sggg.entity.SgLipidRecord;
import org.jeecg.modules.sggg.entity.SgMember;
import org.jeecg.modules.sggg.service.ISgLipidRecordService;
import org.jeecg.modules.sggg.service.ISgMemberService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 血脂记录表
 * @Author: jeecg-boot
 * @Date: 2022-10-17
 * @Version: V1.0
 */
@Api(tags = "血脂记录表")
@RestController
@RequestMapping("/sggg/sgLipidRecord")
@Slf4j
public class SgLipidRecordController extends JeecgController<SgLipidRecord, ISgLipidRecordService> {

    @Autowired
    private ISgLipidRecordService sgLipidRecordService;

    @Autowired
    private ISgMemberService sgMemberService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private ISysDepartService sysDepartController;

    @Autowired
    private ISysUserService sysUserService;

    @ApiOperation(value = "血脂记录表-分页列表查询", notes = "血脂记录表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<SgLipidRecord>> queryPageList(SgLipidRecord sgLipidRecord,
                                                      @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取角色信息
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();
        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {
            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
                sysUser.setId(sysUser1.getId());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgLipidRecord.setResponsibleAgencies(responsibleAgencies);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                List<String> responsibleAgencies = Arrays.asList(array);
                sgLipidRecord.setResponsibleAgencies(responsibleAgencies);
            }
        } else {
            sysUser.setId(sysUser1.getId());
        }
        Page<SgLipidRecord> page = new Page<>(pageNo, pageSize);
        IPage<SgLipidRecord> pageList = sgLipidRecordService.queryList(page, sysUser.getOrgCode(), sgLipidRecord, roleCode, sysUser.getId());
        return Result.OK(pageList);
    }


    /**
     * lx ---- 2022年11月17日 居民详情列表 监测记录
     *
     * @param mid      居民id
     * @param pageNo   当前页
     * @param pageSize 页大小
     * @return 当前页数据
     */
    @GetMapping("/queryListByMid")
    public Result<IPage<SgLipidRecord>> queryListByMid(String mid,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SgLipidRecord> page = new Page<>(pageNo, pageSize);
        IPage<SgLipidRecord> pageList = sgLipidRecordService.page(page, new QueryWrapper<SgLipidRecord>().eq("member_id", mid).orderByDesc("measuring_time"));
        return Result.OK(pageList);
    }

    @ApiOperation(value = "查询居民血压测量记录列表", notes = "查询居民血压测量记录列表")
    @GetMapping(value = "/queryByMemberIdList")
    public Result<List<SgLipidRecord>> queryByMemberIdList(
            @RequestParam(name = "member_id") String member_id) {

        QueryWrapper<SgLipidRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", member_id);
        queryWrapper.orderByDesc("measuring_time");
        List<SgLipidRecord> pageList = sgLipidRecordService.list(queryWrapper);
        if (pageList == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(pageList);
    }

    /**
     * lx ---- 2022年11月18日 居民详情列表 干预记录
     *
     * @param mid 居民id
     * @return 数据
     */
    @GetMapping("/interveneListByMid")
    public Result<List<SgLipidRecord>> interveneListByMid(String mid) {
        return Result.OK(sgLipidRecordService.list(
                new QueryWrapper<SgLipidRecord>()
                        .eq("member_id", mid)
                        .eq("intervene", 2)
                        .select("id", "intervene_content", "intervene_time", "intervene_user")
        ));
    }

    /**
     * wj ---- 2023年03月21日 医生预警列表
     *
     * @param
     * @param pageNo   当前页
     * @param pageSize 页大小
     * @return 当前页数据
     */
    @GetMapping("/queryListByDoctor")
    public Result<IPage<SgLipidRecord>> queryListByDoctor(String doctorId, String name, String phone,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<SgLipidRecord> page = new Page<>(pageNo, pageSize);
        // 获取当前登录人的信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        // 获取当前用户的
        String roleCode = redisUtil.get("roleCode:" + sysUser.getId()).toString();

        SysDepart sysDepart = sysDepartController.getById(sysUser.getDepartIds());
        SysUser sysUser1 = sysUserService.getById(sysUser.getId());
        List<String> responsibleAgencies = new ArrayList<>();
        // 根据DeptAttr机构属性判断当前登录人属于哪个机构（三高之家、三高基地、三高中心）
        if (sysDepart != null && sysDepart.getDeptAttr() != null) {

            // 1.三高之家
            if (sysDepart.getDeptAttr().equals("1")) {
                sysUser.setOrgCode(sysUser1.getOrgCode());
            }
            // 2.三高基地
            if (sysDepart.getDeptAttr().equals("2")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
            }
            // 3.三高中心
            if (sysDepart.getDeptAttr().equals("3")) {
                String[] array = sysUser1.getResponsibleAgency().split(",");
                responsibleAgencies = Arrays.asList(array);
            }
        } else if (roleCode.contains("dept_manage") || roleCode.contains("admin")) {
            sysUser.setOrgCode(sysUser1.getOrgCode());

        } else {
            sysUser.setOrgCode(sysUser1.getOrgCode());
        }
        IPage<SgLipidRecord> pageList = sgLipidRecordService.queryListByDoctor(page, name, phone, responsibleAgencies, sysUser.getOrgCode(), roleCode, sysUser.getId(), "0");
        return Result.OK(pageList);
    }


    @ApiOperation(value = "查询居民待干预测量记录列表", notes = "查询居民待干预测量记录列表")
    @GetMapping(value = "/queryByIdIntervene")
    public Result<List<SgLipidRecord>> queryByIdIntervene(@RequestParam(name = "member_id") String member_id) {
        List<SgLipidRecord> sgLipidRecords = sgLipidRecordService.list(new QueryWrapper<SgLipidRecord>().eq("member_id", member_id).eq("intervene", 0).orderByDesc("measuring_time"));
        if (sgLipidRecords == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgLipidRecords);
    }

    @AutoLog(value = "血脂记录表-添加")
    @ApiOperation(value = "血脂记录表-添加", notes = "血脂记录表-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody SgLipidRecord lr) {
        SgMember m = sgMemberService.getById(lr.getMemberId());
        if (m != null && m.getBloodMax() != null && m.getBloodMin() != null) {
            if (lr.getTotalCholesterol() != null) {
                lr.setIntervene(lr.getTotalCholesterol() >= m.getBloodMax() || lr.getTotalCholesterol() <= m.getBloodMin() ? 0 : 1);
            }
        } else {
            lr.setIntervene(1);
        }
        sgLipidRecordService.save(lr);
        return Result.OK("添加成功！");
    }

    @AutoLog(value = "血脂记录表-编辑")
    @ApiOperation(value = "血脂记录表-编辑", notes = "血脂记录表-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody SgLipidRecord sgLipidRecord) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        sgLipidRecord.setInterveneTime(DateTime.now());
        sgLipidRecord.setInterveneUser(sysUser.getId());
        sgLipidRecord.setMemberName(null);
        sgLipidRecord.setMemberPhone(null);
        sgLipidRecord.setIdCard(null);
        sgLipidRecord.setSex(null);
        sgLipidRecord.setAvatar(null);
        sgLipidRecord.setDoctorName(null);
        sgLipidRecord.setThreeTag(null);
        sgLipidRecord.setBloodWarning(null);
        sgLipidRecordService.updateById(sgLipidRecord);
        return Result.OK("编辑成功!");
    }

    @AutoLog(value = "血脂记录表-通过id删除")
    @ApiOperation(value = "血脂记录表-通过id删除", notes = "血脂记录表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id") String id) {
        sgLipidRecordService.removeById(id);
        return Result.OK("删除成功!");
    }

    @AutoLog(value = "血脂记录表-批量删除")
    @ApiOperation(value = "血脂记录表-批量删除", notes = "血脂记录表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids") String ids) {
        this.sgLipidRecordService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    @ApiOperation(value = "血脂记录表-通过id查询", notes = "血脂记录表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<SgLipidRecord> queryById(@RequestParam(name = "id") String id) {
        SgLipidRecord sgLipidRecord = sgLipidRecordService.getById(id);
        if (sgLipidRecord == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(sgLipidRecord);
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SgLipidRecord sgLipidRecord) {
        return super.exportXls(request, sgLipidRecord, SgLipidRecord.class, "血脂记录表");
    }

    /**
     * 通过excel导入数据
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SgLipidRecord.class);
    }
}
